//
//  SeatViewController.m
//  OrderSeat
//
//  Created by haiming on 13-10-11.
//  Copyright (c) 2013年 wangwei. All rights reserved.
//

#import "SeatViewController.h"
#import "BoxViewController.h"
#import "HallViewController.h"
#import "ShopHomeViewController.h"
#import "LoginViewController.h"

#define DATE_PICKER_HEIGHT      160
#define DONE_TOOLBAR_HEIGHT     30
#define DATE_FORMAT_A           @"yyyy-MM-dd"
#define DATE_FORMAT_B           @"yyyy年MM月dd日"
#define LUNCH_FORMAT_TEXT       @"  午餐12:00"
#define DINNER_FORMAT_TEXT      @"  晚餐/18:00"
#define SEAT_MESSAGE_TEXT      @"已经超过预定时间，请选择其晚餐进行预订！"

@interface SeatViewController ()

@property (nonatomic, copy) NSString *lastwucan;
@property (nonatomic, copy) NSString *lastwancan;
@property (nonatomic, assign) BOOL isTomorrow;

@end

@implementation SeatViewController

- (id)initWithShopId:(NSString*)shopId
{
    self = [super initWithNibClass:[SeatViewController class]];
    if (self) {
        self.shopId = shopId;
        _dataSource = [[SeatDataSource alloc] initWithVC:self];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self setupUI];
    [_dataSource fetchSeatDate];
}

#pragma 隐藏tabbar
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[AppDelegate sharedInstance] hideTabBar:self.tabBarController];
}

#pragma 初始化UI
- (void)setupUI
{
    [self createLeftButton];
    [self setNavigationTitle:@"在线订座"];
    
    [_contectView drawBorder];
    self.shopNameLabel.text = [self.data objectForKey:@"name"];
    
    self.dateTF.text = [self getTodayString];
    self.dateTF.inputView = self.datePicker;
    self.dateTF.inputAccessoryView = _doneBar;
    
    [_doneBtn addTarget:self action:@selector(selectedDateAction:) forControlEvents:UIControlEventTouchUpInside];

    [self.view addTarget:self action:@selector(tapGestureAction:)];
}

#pragma 返回
- (IBAction)leftButtonClick:(id)sender
{
    [[AppDelegate sharedInstance] showTabBar:self.tabBarController];
    [self pushOrPopViewController:[ShopHomeViewController class]];
}

#pragma 选择日期完成后回调函数
- (void)selectedDateAction:(id)sender
{
    NSString *sdate = [_datePicker.date toStringWithFormat:@"yyyy-MM-dd"];
    NSString *ndate = [[NSDate date] toStringWithFormat:@"yyyy-MM-dd"];
    
    if ([sdate compare:ndate] == NSOrderedAscending) {
        [AppDelegate showMessage:@"就餐日期不能小于当前日期！"];
        return;
    }
    
    NSString *date = [_datePicker.date toString];
    NSString *today = [[NSDate date] toString];
    
    if ([date isEqualToString:today]) {
        date = [date stringByAppendingString:@" / 今天"];
    }
    
    [self.dateTF endEditing:YES];
    self.dateTF.text = date;
    
    self.dinnerBtn.selected =
    self.lunchBtn.selected =
    self.boxBtn.selected =
    self.hallBtn.selected =
    self.loungeBtn.selected = NO;
}

#pragma 选择就餐时间: 中餐还是晚餐
- (IBAction)selLunchOrDinnerAction:(UIButton *)sender
{
    if (![self checkTimeForSel:sender]) return;
    
    self.lunchBtn.selected = self.dinnerBtn.selected = NO;
    [sender setSelected:YES];
}

#pragma 选择座位类型
- (IBAction)selSeatAction:(UIButton *)sender
{
    if (!self.dinnerBtn.selected && !self.lunchBtn.selected) {
        [AppDelegate showMessage:@"请选择就餐时间(午餐或晚餐)！"];
        return;
    }
    
    self.boxBtn.selected = self.loungeBtn.selected = self.hallBtn.selected = NO;
    [sender setSelected:YES];
}

#pragma 查询座位信息
- (IBAction)doneAction:(id)sender
{
//    if (![AppDelegate checkLoginWithDelegate:self]) return;
    if (![self checkForm]) return;
    
    int seatType = 1;
    if (self.boxBtn.selected) seatType = 1;
    if (self.loungeBtn.selected) seatType = 2;
    if (self.hallBtn.selected) seatType = 3;
    
    int timeType = self.dinnerBtn.selected ? 2 : 1;
    NSString *ndate = [_datePicker.date toStringWithFormat:DATE_FORMAT_A];
    NSString *dateString = [_datePicker.date toStringWithFormat:DATE_FORMAT_B];
    NSString *time = self.lunchBtn.selected ? LUNCH_FORMAT_TEXT : DINNER_FORMAT_TEXT;
    NSString *orderTime = [dateString stringByAppendingString:time];
    
    NSString *url = [NSString stringWithFormat:API_SEAT_LIST, _shopId,seatType,ndate,timeType];
    
    //去包厢选座位
    if (self.boxBtn.selected) {
        BoxViewController *boxVC = [[BoxViewController alloc] initWithURL:url];
        boxVC.shopId = _shopId;
        boxVC.orderTime = orderTime;
        boxVC.data = self.data;
        
        [self.navigationController pushViewController:boxVC animated:YES];
    }
    //去大厅或者雅座选座位
    else if(self.loungeBtn.selected || self.hallBtn.selected) {
        HallViewController *hallVC = [[HallViewController alloc] initWithURL:url];
        hallVC.shopId = _shopId;
        hallVC.orderTime = orderTime;
        hallVC.data = self.data;
        hallVC.seatType = self.loungeBtn.selected ? Lounge : Hall;
        
        [self.navigationController pushViewController:hallVC animated:YES];
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    LoginViewController *loginVC = [[LoginViewController alloc] init];
    loginVC.backController = self;
    [self.navigationController pushViewController:loginVC animated:YES];
}

- (int)getSeatStateForType:(int)seatType
{
    for (NSDictionary *dic in _dataSource.states) {
        int type  = [[dic objectForKey:@"type"] intValue];
        int state = [[dic objectForKey:@"zhuangtai"] intValue];
        
        if (seatType == type) return state;
    }
    return 1;
}

#pragma 设置预定时间
- (void)setOrderTimes:(NSDictionary *)dic
{
    NSString *text = [dic objectForKey:@"text"];
    _seatDateLabel.text = text;
    
    _lastwucan = [dic objectForKey:@"lastwucan"];
    _lastwancan = [dic objectForKey:@"lastwancan"];
}

#pragma 获取今天日期格式
- (NSString *)getTodayString
{
    NSString *today = [[NSDate date] toString];
    today = [today stringByAppendingString:@" / 今天"];
    return today;
}

#pragma 鼠标点击其他位置隐藏键盘
- (void)tapGestureAction:(id)sender
{
    [_dateTF resignFirstResponder];
}

#pragma 检查预定时间
- (BOOL)checkTimeForSel:(id)sender
{
    NSString *selDate = [_datePicker.date toStringWithFormat:@"yyyyMMdd"];
    NSString *curDate = [[NSDate date] toStringWithFormat:@"yyyyMMdd"];
    
    if ([selDate compare:curDate] == NSOrderedSame) {
        NSString *hour = [[NSDate date] toStringWithFormat:@"H.m"];
        
        if ([sender tag] == _lunchBtn.tag) {
            if ([hour floatValue] > [_lastwucan floatValue] && [hour floatValue] > [_lastwancan floatValue]) {
                NSDate *date = [[NSDate date] dateByAddingTimeInterval:3600*24];
                _datePicker.date = date;
                self.dateTF.text = [date toString];
                _isTomorrow = YES;
                [AppDelegate showMessage:@"您已经超过了当前餐厅的最晚预定时间，只能预定明天的座位"];
                return YES;
            }
            else if ([hour floatValue] > [_lastwucan floatValue] && [hour floatValue] <= [_lastwancan floatValue]) {
                [AppDelegate showMessage:SEAT_MESSAGE_TEXT];
                return NO;
            }
        }
        
        if ([sender tag] == _dinnerBtn.tag) {
            _isTomorrow = NO;
            if ([hour floatValue] > [_lastwancan floatValue]) {
                NSDate *date = [[NSDate date] dateByAddingTimeInterval:3600*24];
                _datePicker.date = date;
                self.dateTF.text = [date toString];
                _isTomorrow = YES;
                [AppDelegate showMessage:@"您已经超过了当前餐厅的最晚预定时间，只能预定明天的座位"];
                return YES;
            }
        }
    }
    
    return YES;
}

#pragma 校验表单必须条件
- (BOOL)checkForm
{
    if (!self.dinnerBtn.selected && !self.lunchBtn.selected) {
        [AppDelegate showMessage:@"请选择就餐时间(午餐、晚餐)！"];
        return NO;
    }
    
    if (!self.boxBtn.selected && !self.loungeBtn.selected && !self.hallBtn.selected) {
        [AppDelegate showMessage:@"请选择餐位类型(包厢、雅座、大厅)！"];
        return NO;
    }
    
    return YES;
}

@end

//========================================================================================
#pragma======数据源实现=====================================================================
//========================================================================================

#define SEAT_STATE_TAG 1001
#define SEAT_DATE_TAG 1002

@implementation SeatDataSource

- (id)initWithVC:(id)viewController
{
    self = [super init];
    if (self) {
        self.viewController = viewController;
    }
    return self;
}

#pragma 获取座位状态
- (void)fetchSeatState:(NSString *)shopId date:(NSString *)date timeType:(NSInteger)type
{
    [SVProgressHUD show];
    NSString *url = [NSString stringWithFormat:API_SEAT_STATE, shopId, date, type];
    [self get:url tag:SEAT_STATE_TAG];
}

- (void)fetchSeatDate
{
    [SVProgressHUD show];
    NSString *url = [NSString stringWithFormat:API_SEAT_DATE, _viewController.shopId];
    [self get:url tag:SEAT_DATE_TAG];
}

- (void)requestFinished:(ASIHTTPRequest *)request
{
    [SVProgressHUD dismiss];
    
    NSDictionary *json = [request.responseData JSONValue];
    
    if (request.tag == SEAT_STATE_TAG) {
        self.states = [json objectForKey:@"zhuangtai"];
        
        NSString *shuoming = [json objectForKey:@"shuoming"];
        if (![shuoming isEqualToString:S_EMPTY]) {
            _viewController.seatDateLabel.text = shuoming;
        }
    }
    
    if (request.tag == SEAT_DATE_TAG) {
        [_viewController setOrderTimes:json];
    }
}

@end





// 073000185319
// 43564224